﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;



namespace Gnosis.Alexandria.Controllers
{
    public abstract class ControllerOldBase
        : IControllerOld
    {
        public ControllerOldBase(IControllerOld parent)
        {
            _parent = parent;
        }

        private readonly IControllerOld _parent;
        private readonly IList<IControllerOld> _children = new List<IControllerOld>();

        protected void AddChild(IControllerOld child)
        {
            _children.Add(child);
        }

        protected void SendChildren(IMessageOld message)
        {
            foreach (IControllerOld child in _children)
                child.Send(this, message);
        }

        protected void SendParent(IMessageOld message)
        {
            if (_parent != null)
                _parent.Send(this, message);
        }

        protected abstract void HandleMessage(IMessageOld message);

        public IControllerOld Parent
        {
            get { return _parent; }
        }

        public IEnumerable<IControllerOld> Children
        {
            get { return _children; }
        }

        public IMessageOld CreateMessage(string type)
        {
            return CreateMessage(type, null);
        }

        public IMessageOld CreateMessage(string type, object body)
        {
            return new Message(type, body);
        }

        public void Send(object sender, IMessageOld message)
        {
            HandleMessage(message);

            if (Parent != null && sender != Parent)
                Parent.Send(this, message);

            foreach (IControllerOld child in _children)
                if (sender != child)
                    child.Send(this, message);
        }

        public void Send(object sender, string type)
        {
            Send(sender, CreateMessage(type));
        }

        public void Send(object sender, string type, object body)
        {
            Send(sender, CreateMessage(type, body));
        }
    }
}
